<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="RxJava2," />










<meta name="description" content="RxJava2学习笔记，基于io.reactivex.rxjava2:rxjava:2.1.10">
<meta name="keywords" content="RxJava2">
<meta property="og:type" content="article">
<meta property="og:title" content="RxJava2源码分析">
<meta property="og:url" content="http://yoursite.com/2018/09/13/RxJava2源码分析/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="RxJava2学习笔记，基于io.reactivex.rxjava2:rxjava:2.1.10">
<meta property="og:locale" content="default">
<meta property="og:updated_time" content="2018-09-13T08:23:38.974Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="RxJava2源码分析">
<meta name="twitter:description" content="RxJava2学习笔记，基于io.reactivex.rxjava2:rxjava:2.1.10">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/09/13/RxJava2源码分析/"/>





  <title>RxJava2源码分析 | Hexo</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="default">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Hexo</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/09/13/RxJava2源码分析/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Ruge">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Hexo">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">RxJava2源码分析</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-09-13T15:00:19+08:00">
                2018-09-13
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/RxJava2/" itemprop="url" rel="index">
                    <span itemprop="name">RxJava2</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>RxJava2学习笔记，基于<code>io.reactivex.rxjava2:rxjava:2.1.10</code><br><a id="more"></a></p>
<h3 id="基础"><a href="#基础" class="headerlink" title="基础"></a>基础</h3><p>RxJava简单的使用如下：</p>
<pre><code>Observable.create(new ObservableOnSubscribe&lt;String&gt;() {
            @Override
            public void subscribe(ObservableEmitter&lt;String&gt; emitter) throws Exception {
                emitter.onNext(&quot;aaa&quot;);
                emitter.onNext(&quot;zzz&quot;);
                emitter.onComplete();
            }
        }).subscribe(new Observer&lt;String&gt;() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String s) {
                Log.d(&quot;xcx&quot;, &quot;onNext: &quot;+s);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                Log.d(&quot;xcx&quot;, &quot;onComplete: &quot;);
            }
        });
</code></pre><h3 id="Observable-create"><a href="#Observable-create" class="headerlink" title="Observable.create"></a>Observable.create</h3><p>我们看一下create()方法做了什么：</p>
<pre><code>public static &lt;T&gt; Observable&lt;T&gt; create(ObservableOnSubscribe&lt;T&gt; source) {
         //判断空值
        ObjectHelper.requireNonNull(source, &quot;source is null&quot;);
        return RxJavaPlugins.onAssembly(new ObservableCreate&lt;T&gt;(source));
    }
</code></pre><p>调用onAssembly()方法，传入一个ObservableCreate类，并且将我们在create传入的ObservableOnSubscribe作为构造参数传入。</p>
<h4 id="看一下onAssembly："><a href="#看一下onAssembly：" class="headerlink" title="看一下onAssembly："></a>看一下onAssembly：</h4><pre><code>public static &lt;T&gt; Observable&lt;T&gt; onAssembly(@NonNull Observable&lt;T&gt; source) {
        Function&lt;? super Observable, ? extends Observable&gt; f = onObservableAssembly;
        if (f != null) {
            return apply(f, source);
        }
        return source;
    }
</code></pre><p>如果onObservableAssembly为空，则返回source。onObservableAssembly在哪里赋值的呢？在这里：</p>
<pre><code>setOnObservableAssembly(null);
public static void setOnObservableAssembly(@Nullable Function&lt;? super Observable, ? extends Observable&gt; onObservableAssembly) {
    if (lockdown) {
        throw new IllegalStateException(&quot;Plugins can&apos;t be changed anymore&quot;);
    }
    RxJavaPlugins.onObservableAssembly = onObservableAssembly;
}
</code></pre><p>可以看出，这一步只是将Observable做了封装，传入什么就返回了什么。RxJava中还有很多这样的方法，碰到我们再说。此时转入ObservableCreate类中。</p>
<h4 id="ObservableCreate类"><a href="#ObservableCreate类" class="headerlink" title="ObservableCreate类"></a>ObservableCreate类</h4><p>这一步只是将我们传入的source保存了起来，此时完成了observable的创建任务，是何时订阅的呢？没错，就是在subscribe()方法中订阅的。接下来看subscribe(Observer)方法</p>
<pre><code>public final class ObservableCreate&lt;T&gt; extends Observable&lt;T&gt; {
    final ObservableOnSubscribe&lt;T&gt; source;

    public ObservableCreate(ObservableOnSubscribe&lt;T&gt; source) {
        this.source = source;
    }

    @Override
    protected void subscribeActual(Observer&lt;? super T&gt; observer) {
        CreateEmitter&lt;T&gt; parent = new CreateEmitter&lt;T&gt;(observer);
        observer.onSubscribe(parent);

        try {
            source.subscribe(parent);
        } catch (Throwable ex) {
            Exceptions.throwIfFatal(ex);
            parent.onError(ex);
        }
    }

    static final class CreateEmitter&lt;T&gt;
    extends AtomicReference&lt;Disposable&gt;
    implements ObservableEmitter&lt;T&gt;, Disposable { ... }
}
</code></pre><h3 id="Observable-subscribe-Observer"><a href="#Observable-subscribe-Observer" class="headerlink" title="Observable#subscribe(Observer)"></a>Observable#subscribe(Observer<t>)</t></h3><pre><code>public final void subscribe(Observer&lt;? super T&gt; observer) {
        ObjectHelper.requireNonNull(observer, &quot;observer is null&quot;);
        try {
              //调用onSubscribe，跟onAssembly一样，返回了传入的observer
            observer = RxJavaPlugins.onSubscribe(this, observer);

            ObjectHelper.requireNonNull(observer, &quot;Plugin returned null Observer&quot;);
            //核心代码，传入observer
            subscribeActual(observer);
        } catch (NullPointerException e) { // NOPMD
            throw e;
        } catch (Throwable e) {
            Exceptions.throwIfFatal(e);
            // can&apos;t call onError because no way to know if a Disposable has been set or not
            // can&apos;t call onSubscribe because the call might have set a Subscription already
            RxJavaPlugins.onError(e);

            NullPointerException npe = new NullPointerException(&quot;Actually not, but can&apos;t throw other exceptions due to RS&quot;);
            npe.initCause(e);
            throw npe;
        }
    }
</code></pre><p>细心的你看到了么？调用了<code>subscribeActual(observer);</code>这个方法，上面ObservableCreate类也有相同的方法。是巧合么？肯定不是啦。这个方法在Observable中：</p>
<pre><code>protected abstract void subscribeActual(Observer&lt;? super T&gt; observer);
</code></pre><p>上面提到过ObservableCreate类，它继承了了Observable，实现了<code>subscribeActual(observer);</code>这个方法。当我们调用subscribe时，其实就是调用了ObservableCreate实现方法。</p>
<pre><code>ObservableCreate类的subscribeActual

@Override
protected void subscribeActual(Observer&lt;? super T&gt; observer) {
    CreateEmitter&lt;T&gt; parent = new CreateEmitter&lt;T&gt;(observer);
    observer.onSubscribe(parent);

    try {
        source.subscribe(parent);
    } catch (Throwable ex) {
        Exceptions.throwIfFatal(ex);
        parent.onError(ex);
    }
}
</code></pre><p>调用source就是我们传入的ObservableOnSubscribe的onSubscribe开始传输数据。</p>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>整个过程其实分三步：</p>
<ol>
<li>创建ObservableCreate类该类继承了Observable，实现了<code>subscribeActual()</code>方法。</li>
<li>调用ObservableCreate的<code>subscribe()</code>方法，内部调用了第一步的<code>subscribeActual()</code></li>
<li><code>subscribeActual()</code>内部调用了ObservableOnSubscribe的subscribe()方法，开始传输数据。</li>
</ol>
<p>把observer的引用传给了Observable，从而可以调用observer的方法。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/RxJava2/" rel="tag"># RxJava2</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/09/13/加油/" rel="next" title="接下来该做的事儿">
                <i class="fa fa-chevron-left"></i> 接下来该做的事儿
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/01/09/Activity启动模式/" rel="prev" title="Activity启动模式">
                Activity启动模式 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">Ruge</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">8</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">categories</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">tags</span>
                
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#基础"><span class="nav-number">1.</span> <span class="nav-text">基础</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Observable-create"><span class="nav-number">2.</span> <span class="nav-text">Observable.create</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#看一下onAssembly："><span class="nav-number">2.1.</span> <span class="nav-text">看一下onAssembly：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#ObservableCreate类"><span class="nav-number">2.2.</span> <span class="nav-text">ObservableCreate类</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Observable-subscribe-Observer"><span class="nav-number">3.</span> <span class="nav-text">Observable#subscribe(Observer)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#总结"><span class="nav-number">4.</span> <span class="nav-text">总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Ruge</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
